package com.nacos.config.configuration;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author chn
 * @Feature: 配置监听
 * @version 1.0
 * @data 2024/9/12 11:32
 */
public class listenerConfiguration {
    public static void main(String[] args) throws NacosException, IOException {
        Properties properties = new Properties();
        // 配置地址、用户名、密码
        properties.put("serverAddr", "localhost:8848");
        properties.put("username", "nacos");
        properties.put("password", "nacos");

        ConfigService configService = NacosFactory.createConfigService(properties);
        NamingService namingService = NacosFactory.createNamingService(properties);

        // 监听配置
        Listener listener = new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("recieve1:" + configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        };
        configService.addListener("user", "DEFAULT_GROUP", listener);

        boolean running = true;
        while (running) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (namingService == null) {
                // 删除监听
                configService.removeListener("user", "DEFAULT_GROUP", listener);
                running = false;
            }
        }


    }
}
